﻿using System;
using System.Collections.Concurrent;

namespace CheckTicket.Sample
{
    public class MessageBus
    {
        private MessageBus()
        {
        }

        private static volatile object _instanceLock = new();
        private static MessageBus _instance;

        public static MessageBus Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_instanceLock)
                    {
                        if (_instance == null)
                        {
                            _instance = new MessageBus();
                        }
                    }
                }

                return _instance;
            }
        }

        private readonly ConcurrentQueue<string> _messages = new ConcurrentQueue<string>();

        /// <summary>
        /// 接收到消息
        /// </summary>
        public event Action<string> Received;

        public void Enqueue(string message)
        {
            _messages.Enqueue(message);
            OnReceived(message);
        }

        public string Receive()
        {
            if (_messages.TryDequeue(out var message))
                return message;
            return null;
        }

        protected virtual void OnReceived(string message)
        {
            Received?.Invoke(message);
        }
    }
}